import axios from "axios";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import Qs from "query-string";
let loading;
let logout = false;
const reqQueue = [];

const service = axios.create({
	baseURL: import.meta.env.VITE_APP_AXIOS_URL_TX, // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 30000, // request timeout
	withCredentials: true, //允许携带cookie
});
const generateReqKey = (config) => {
	const { method, url, params, data } = config;
	return [method, url, Qs.stringify(params), Qs.stringify(data)].join("&");
};
service.interceptors.request.use(
	(config) => {
		const myConfig = config;

		if (myConfig.method === "post" || myConfig.method === "put") {
			reqQueue.push(generateReqKey(config));

			// if (!loading) {
			//   loading = ElLoading.service({
			//     lock: true,
			//     text: "Loading",
			//     background: "rgba(0, 0, 0, 0.7)",
			//   });
			// }
		} else if (myConfig.method === "get") {
			myConfig.params = {
				...myConfig.params,
				_t: Date.parse(new Date()) / 1000,
			};
		}

		return myConfig;
	},
	(error) => {
		// do something with request error
		return Promise.reject(error);
	}
);
const cancelLoading = (config) => {
	if (config.method === "post" || config.method === "put") {
		reqQueue.splice(
			reqQueue.findIndex((item) => item === generateReqKey(config)),
			1
		);
		// if (loading && reqQueue.length === 0) {
		//   loading.close();
		//   loading = "";
		// }
	}
};
service.interceptors.response.use(
	(response) => {
		const { config } = response;
		cancelLoading(config);
		const res = response.data;
		if (!res.status) {
			return res;
		}
		return res;
	},
	(error) => {
		cancelLoading(error.toJSON().config);

		if (error.toJSON().code === "ECONNABORTED") {
			ElMessage({
				message: "服务响应超时",
				type: "error",
				duration: 5 * 1000,
			});
		} else if (error.toJSON().status === 503) {
			ElMessage({
				message: "服务不可用",
				type: "error",
				duration: 5 * 1000,
			});
			// console.log(router, 'kkk');
			router.push(`/502?redirect=/`);
		} else if (error.toJSON().status === 500) {
			ElMessage({
				message: "服务状态异常",
				type: "error",
				duration: 5 * 1000,
			});
		} else if (error.toJSON().status === 404) {
			ElMessage({
				message: "接口路径异常",
				type: "error",
				duration: 5 * 1000,
			});
		} else {
			ElMessage({
				message: error.toJSON().message,
				type: "error",
				duration: 5 * 1000,
			});
		}

		return Promise.reject(error);
	}
);
export default service;
